//
//  RegisterInfoController.m
//  Arts1
//
//  Created by apple on 15/9/22.
//  Copyright © 2015年 Arts1. All rights reserved.
//

#import "RegisterInfoController.h"
#import "AllHeader.h"
#import <QuartzCore/QuartzCore.h>
#import <QuartzCore/CoreAnimation.h>
#import <MobileCoreServices/UTCoreTypes.h>
#import "LoginViewController.h"
#import "HomeListViewController.h"
#import "ZHPickView.h"

//设置个人资料
//#define kURL @"http://arts1.dlab.com.cn/app/changeinfo"
#define kURL @"http://arts1.cn/app/changeinfo"


//设置姓名
//#define kNickNameURL @"http://arts1.dlab.com.cn/app/setname"
#define kNickNameURL @"http://arts1.cn/app/setname"


//设置头像
//#define kSetFace @"http://arts1.dlab.com.cn/app/setface"
#define kSetFace @"http://arts1.cn/app/setface"

@interface RegisterInfoController ()<ZHPickViewDelegate>

//菊花控件
@property (nonatomic ,strong) MBProgressHUD *HUD;

@property(nonatomic,strong)ZHPickView *pickview;

@end

@implementation RegisterInfoController

- (void)viewDidLoad
{
    [super viewDidLoad];
    //修饰视图
    [self modifySubview];
    //设置头像
    [self requestIconPhoto];
    //设置点击编辑头像问题手势
    [self setEditIconTapGesture];
}

// 修饰视图
- (void)modifySubview
{
    //设置背景颜色
    self.view.backgroundColor = kCustomColor(250, 250, 250, 1.0);
    
    //确认按钮
    _sureButton.layer.cornerRadius = 4;
    _sureButton.layer.masksToBounds = YES;
    
    //头像设置成圆形
    _iconImage.layer.cornerRadius = 40;
    _iconImage.userInteractionEnabled = YES;
    
    //打开编辑头像Label的用户交互
    _editIcon.userInteractionEnabled = YES;
    
    //背景视图设置圆角
    _backView.layer.cornerRadius = 5;
    //背景视图添加阴影
    [UIView viewShadowColor:_backView];
    
    // 头部视图加阴影
    [UIView viewWideForShadowColor:_topView];
}

//  选择所在城市
- (IBAction)selectCity:(id)sender {
    _pickview=[[ZHPickView alloc] initPickviewWithPlistName:@"city" isHaveNavControler:NO];
    _pickview.delegate=self;
    [_pickview show];
}

#pragma mark ZhpickVIewDelegate

-(void)toobarDonBtnHaveClick:(ZHPickView *)pickView resultString:(NSString *)resultString{
    _txtProvince.text = resultString;
}


//移除键盘
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
    [_pickview remove];
}

//设置头像
- (void)requestIconPhoto
{
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setPhoto:)];
    [_iconImage addGestureRecognizer:tapGesture];
}
//设置点击编辑头像设置手势
- (void)setEditIconTapGesture
{
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(setPhoto:)];
    [_editIcon addGestureRecognizer:tapGesture];
}

//获取点击头像后的方法，设置模糊页面
- (void)setPhoto:(UITapGestureRecognizer *)setPhoto
{
    _gesture = [[SetPhotoController alloc] init];
    [UIView viewShadowColor:_gesture.view];
    [self.view addSubview:_gesture.view];
    __weak RegisterInfoController *resisterVC = self;
    
    //调用相册和相机方法
    resisterVC.gesture.photoBlock = ^(NSInteger num)
    {
        if (num == 0)
        {
            //调用相册方法
            [resisterVC selectExistingPictureOrVideo];
        }
        else
        {
            //调用相机方法
            [resisterVC shootPiicturePrVideo];
        }
    };
    
    _gesture.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
}

//设置基本资料数据请求
- (void)requestData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    
    
    //结束注册完成返回的两个值（uid和key）
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    NSString *uid = dic[@"data"][@"uid"];
    
    NSString *key = dic[@"data"][@"key"];
    
    NSDictionary *pardic = nil;
    
    NSString *sex = nil;
    
    //如果选择第一个返回男，否则返回女
    if (_sexSegment.selectedSegmentIndex == 0)
    {
        sex = @"男";
    }
    else
    {
        sex = @"女";
    }
    //判断uid和key不能为空的情况下才能请求
    
    if (_txtName.text.length == 0)
    {
        [MBProgressHUD show:@"姓名不能为空" icon:nil view:self.view];
        return;
    }
    if (_txtProvince.text.length == 0)
    {
        [MBProgressHUD show:@"省份不能为空" icon:nil view:self.view];
        return;
    }
    if (uid && key)
    {
        pardic = @{@"uid":uid,
                   @"key":key,
                   @"nickName":_txtName.text,
                   @"Province":_txtProvince.text,
                   @"gender":sex};
    }
    
    [manage POST:kURL parameters:pardic
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary * sender = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers| NSJSONReadingMutableLeaves) error:nil];
             NSLog(@"--------%@",sender);
             
             //服务器返回的状态
             int index = [sender[@"status"] intValue];
             NSString *statusStr = nil;
             switch (index)
             {
                 case 1:
                 {
                     statusStr = @"设置成功";
                     
                     
                     [self dismissViewControllerAnimated:NO completion:^{
                         
                     }];
                     NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
                     NSNotification *notification = [[NSNotification alloc]initWithName:@"RegiserAndSetting" object:nil userInfo:nil];
                     [center postNotification:notification];
                     
                 }
                     break;
                 case -3:
                     statusStr = @"昵称不符合规范";
                     break;
                 default:
                     break;
             }
             //只有返回这两个值的时候才弹出提示框
             if (index == 1 || index == -3)
             {
                 // 请求成功的时候调用这个block
                 [MBProgressHUD show:statusStr icon:nil view:self.view];
             }
             
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

/**
 *  设置头像数据请求
 */
- (void)setIconImageRquest
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"multipart/form-data"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //压缩图片
    NSData *imageData = UIImageJPEGRepresentation(_iconImage.image, 1.0);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@.png",str];
    
    
    //结束注册完成返回的两个值（uid和key）
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    
    NSString *uid = dic[@"data"][@"uid"];
    
    NSString *key = dic[@"data"][@"key"];
    
    NSDictionary *pardic = nil;
    
    
    if (uid && key)
    {
        pardic = @{@"uid":uid,
                   @"key":key};
    }
    
    [manage POST:kSetFace parameters:pardic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData)
    {
        
        if (imageData)
        {
            //设置图片的格式
           [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
        }
        
        
    } success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject)
    {
        
        //请求成功
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        //请求失败
    }];
}

//确认（注册）
- (IBAction)sureButton:(UIButton *)sender
{
    
    //设置头像请求数据请求
    [self setIconImageRquest];
    //设置基本资料数据请求
    [self requestData];
}


//从相机上选择
- (void)shootPiicturePrVideo
{
    [self getMediaFromSource:UIImagePickerControllerSourceTypeCamera];
}

//从相册中选择
- (void)selectExistingPictureOrVideo
{
    [self getMediaFromSource:UIImagePickerControllerSourceTypePhotoLibrary];
}

//用户选中图片后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //获得编辑过的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //设置头像是圆形
    _iconImage.layer.cornerRadius = 40;
    _iconImage.layer.masksToBounds = YES;
    //回调给头像赋值
    _iconImage.image = image;
    //移除模糊页面视图
    [_gesture.view removeFromSuperview];

    //如果不选择的话，可以返回原来的页面
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

// 用户选择取消
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    //如果不选择的话，可以返回原来的页面
    [picker dismissViewControllerAnimated:NO completion:nil];
    
}

//根据用户选取的类型(相册或者相机)来判断当前状态是否支持该功能
-(void)getMediaFromSource:(UIImagePickerControllerSourceType)sourceType
{
    NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
    
    if([UIImagePickerController isSourceTypeAvailable:sourceType] &&[mediatypes count]>0)
    {
        NSArray *mediatypes = [UIImagePickerController availableMediaTypesForSourceType:sourceType];
        
        UIImagePickerController *picker=[[UIImagePickerController alloc] init];
        
        picker.mediaTypes = mediatypes;
        
        picker.delegate = self;
        
        picker.allowsEditing = YES;
        
        picker.sourceType = sourceType;
        
        NSString *requiredmediatype = (NSString *)kUTTypeImage;
        
        NSArray *arrmediatypes = [NSArray arrayWithObject:requiredmediatype];
        
        [picker setMediaTypes:arrmediatypes];
        
        [self presentViewController:picker animated:YES completion:^{
            
        }];
    }
    else
    {
        //如果不支持拍摄功能就弹出提示
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"错误信息!" message:@"当前设备不支持拍摄功能" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
